<!--
  应用管理主页面
  @description SOP应用管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('sop.app.appName')" prop="appName">
        <el-input
          v-model="queryParams.appName"
          :placeholder="t('sop.common.pleaseInput') + t('sop.app.appName')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.app.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('sop.common.pleaseInput') + t('sop.app.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.app.appStatus')" prop="appStatus">
        <el-select
          v-model="queryParams.appStatus"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.app.appStatus')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in appStatusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.app.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="t('sop.common.startTime')"
          :end-placeholder="t('sop.common.endTime')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('sop.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('sop.common.reset') }}
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['sop:app:create']">
          <Icon class="mr-5px" icon="ep:plus" />
          {{ t('sop.common.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['sop:app:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('sop.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column :label="t('sop.app.appId')" align="center" prop="appId" width="200">
        <template #default="scope">
          <el-text class="app-id-text" copyable>{{ scope.row.appId }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.app.appName')"
        align="center"
        prop="appName"
        min-width="150"
      />
      <el-table-column
        :label="t('sop.app.merchantNo')"
        align="center"
        prop="merchantNo"
        width="180"
      />
      <el-table-column
        :label="t('sop.app.merchantName')"
        align="center"
        prop="merchantName"
        min-width="150"
      />
      <el-table-column :label="t('sop.app.appStatus')" align="center" prop="appStatus" width="100">
        <template #default="scope">
          <el-tag :type="getAppStatusTagType(scope.row.appStatus)">
            {{ appStatusOptions[scope.row.appStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.app.rateLimitPerSecond')"
        align="center"
        prop="rateLimitPerSecond"
        width="120"
      >
        <template #default="scope">
          <el-tag type="info">{{ scope.row.rateLimitPerSecond }}/s</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.app.rateLimitPerMinute')"
        align="center"
        prop="rateLimitPerMinute"
        width="120"
      >
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.rateLimitPerMinute }}/m</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.common.createTime')"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column :label="t('sop.common.operation')" align="center" width="280" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['sop:app:query']"
          >
            {{ t('sop.common.view') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['sop:app:update']"
          >
            {{ t('sop.common.edit') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleStatusChange(scope.row, AppStatusEnum.ENABLED)"
            v-hasPermi="['sop:app:update']"
            v-if="scope.row.appStatus === AppStatusEnum.DISABLED"
          >
            {{ t('sop.app.enable') }}
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleStatusChange(scope.row, AppStatusEnum.DISABLED)"
            v-hasPermi="['sop:app:update']"
            v-if="scope.row.appStatus === AppStatusEnum.ENABLED"
          >
            {{ t('sop.app.disable') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sop:app:delete']"
          >
            {{ t('sop.common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 应用表单 -->
  <AppForm ref="formRef" @success="getList" />

  <!-- 应用详情 -->
  <AppDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import {
  getAppInfoPageApi,
  deleteAppInfoApi,
  updateAppStatusApi,
  exportAppInfoApi
} from '@/api/sop/app'
import type { AppVO, AppPageReqVO } from '@/api/sop/types'
import { AppStatusEnum } from '@/api/sop/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import AppForm from './AppForm.vue'
import AppDetail from './AppDetail.vue'

defineOptions({ name: 'SopApp' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<AppVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<AppPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  appName: undefined,
  merchantNo: undefined,
  appStatus: undefined,
  createTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const formRef = ref()
const detailRef = ref()

// 选项数据
const appStatusOptions = {
  [AppStatusEnum.ENABLED]: t('sop.app.appStatuses.enabled'),
  [AppStatusEnum.DISABLED]: t('sop.app.appStatuses.disabled')
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getAppInfoPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询应用列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 新增/修改操作
 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/**
 * 查看详情
 */
const openDetail = (row: AppVO) => {
  detailRef.value.open(row)
}

/**
 * 状态变更
 */
const handleStatusChange = async (row: AppVO, status: number) => {
  const action = status === AppStatusEnum.ENABLED ? t('sop.app.enable') : t('sop.app.disable')
  try {
    await ElMessageBox.confirm(
      t('sop.app.tips.statusChangeConfirm', { action, appName: row.appName }),
      t('sop.common.confirmTitle'),
      {
        confirmButtonText: t('sop.common.confirm'),
        cancelButtonText: t('sop.common.cancel'),
        type: 'warning'
      }
    )

    await updateAppStatusApi(row.id, status)
    ElMessage.success(t('sop.app.tips.statusChangeSuccess'))
    await getList()
  } catch (error) {
    console.error('更新应用状态失败:', error)
  }
}

/**
 * 删除操作
 */
const handleDelete = async (row: AppVO) => {
  try {
    await ElMessageBox.confirm(
      t('sop.app.tips.deleteConfirm', { appName: row.appName }),
      t('sop.common.confirmTitle'),
      {
        confirmButtonText: t('sop.common.confirm'),
        cancelButtonText: t('sop.common.cancel'),
        type: 'warning'
      }
    )

    await deleteAppInfoApi(row.id)
    ElMessage.success(t('sop.app.tips.deleteSuccess'))
    await getList()
  } catch (error) {
    console.error('删除应用失败:', error)
  }
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportAppInfoApi(queryParams)
    message.success(t('sop.common.exportSuccess'))
  } catch (error) {
    console.error('导出应用数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getAppStatusTagType = (status: number) => {
  const statusMap = {
    [AppStatusEnum.ENABLED]: 'success',
    [AppStatusEnum.DISABLED]: 'danger'
  }
  return statusMap[status] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-id-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}
</style>
